import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/cache/id_cache.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/user_model.dart';
import 'package:wu_you/page/mall/page_product_order.dart';
import 'package:wu_you/page/trad/page_payment_methed.dart';
import 'package:wu_you/page/trad/page_trad_type.dart';
import 'package:wu_you/page/user/page_address_manager.dart';
import 'package:wu_you/page/user/page_funds_list.dart';
import 'package:wu_you/page/user/page_password.dart';
import 'package:wu_you/page/user/page_setting.dart';
import 'package:wu_you/page/user/page_share.dart';
import 'package:wu_you/page/user/page_transfer_money.dart';
import 'package:wu_you/page/user/page_version.dart';
import 'package:wu_you/page/user/page_withdraw.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/user_bloc.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:wu_you/widgets/image_label.dart';

///我的
class MinePage extends StatefulWidget{
  @override
  MinePageState createState() => MinePageState();
}
class MinePageState extends State<MinePage>{
  @override
  void initState() {
    super.initState();
  }

  var message;
  BuildContext ctx;

  Future<Null> _userRefresh() {
    return Future.delayed(Duration(seconds: 1), () {
      BlocProvider.of<UserInfoBloc>(ctx).add(HttpEvent());
    });
  }
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return MultiBlocProvider(
      providers: [
        BlocProvider.value(value: UserInfoBloc()),
      ],
      child: Scaffold(
        backgroundColor: HexColor("#F8F8F8"),
        body: HttpWidget<UserInfoModel, UserInfoBloc>(
        create: (context) => BlocProvider.of<UserInfoBloc>(context)..add(HttpEvent()),
          child: (context, data) {
            ctx = context;
            UserIdCache().save(data.id);
            UserPhoneCache().save(data.phone);
            return RefreshIndicator(
              onRefresh: _userRefresh,
              displacement: 40,
              notificationPredicate: defaultScrollNotificationPredicate,
              child: CustomScrollView(
                slivers: [
                  SliverAppBar(
                    elevation: 0,
                    titleSpacing: 4,
                    leading: null,
                    automaticallyImplyLeading: false,
                    primary: true,
                    floating: false,
                    pinned: true,
                    snap: false,
                    actions: [
                      IconButton(onPressed: (){
                        NavigatorUtil.navigateToPage(context, SettingPage());
                      }, icon: Icon(Icons.settings,color: Colors.white,))
                    ],
                    backgroundColor: HexColor("#F8F8F9"),
                    title: Text("${message['tabUser']}"),
                    toolbarHeight: 56,
                    expandedHeight: MediaQuery.of(context).size.width / 1.6,
                    flexibleSpace: _buildFlexibleSpace(data),
                  ),

                  SliverToBoxAdapter(
                    child: Row(
                      children: [
                        Flexible(
                          child: Container(
                              height: 80,
                              width: double.infinity,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(5)),
                                color: Colors.white,
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceAround,
                                children: [
                                  Column(
                                    mainAxisSize: MainAxisSize.min,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text("${message['user3']}",style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),),
                                      SizedBox(height: 5,),
                                      Text("${message['user3']}",style: TextStyle(fontSize: 14,color: AppColors.textHintColor),)
                                    ],
                                  ),
                                  Image.asset(Utils.getImgPath('ic_user_share'),width: 45,height: 45,)
                                ],
                              )
                          ).addGesture(() {
                            if(double.parse(data.ach) <= 0){
                              ToastUtils.show('您还没有消费记录，请消费后再推广。', context,dur: 3);
                              return;
                            }
                            NavigatorUtil.navigateToPage(context, SharePage());
                          }),
                          flex: 1,
                        ),
                        SizedBox(width: 8,),
                        Flexible(
                            flex: 1,
                            child: Container(
                                height: 80,
                                width: double.infinity,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(Radius.circular(6)),
                                    color: Colors.white
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                                  children: [
                                    Column(
                                      mainAxisSize: MainAxisSize.min,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text("${message['user4']}",style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),),
                                        SizedBox(height: 5,),
                                        Text("${message['user4']}",style: TextStyle(fontSize: 14,color: AppColors.textHintColor),)
                                      ],
                                    ),
                                    Image.asset(Utils.getImgPath('ic_user_trading'),width: 45,height: 45,)
                                  ],
                                )
                            ).addGesture(() {
                              if(data.phone != null && data.phone != ""){
                                NavigatorUtil.navigateToPage(context, TradTypePage()).then((value){
                                  BlocProvider.of<UserInfoBloc>(ctx).add(HttpEvent());
                                });
                              }else{
                                ToastUtils.show("请先实名绑定银行卡", context);
                              }
                            })
                        )
                      ],
                    ).addPadding(EdgeInsets.all(12)),
                  ),

                  SliverToBoxAdapter(
                    child: Container(
                      margin: EdgeInsets.only(left: 12,right: 12),
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(6)),
                          color: Colors.white
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("${message['user5']}",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16),),
                          SizedBox(height: 8,),
                          Divider(thickness: 1,),
                          SizedBox(height: 6,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              _buildMallItem(0,'${message['user6']}','ic_order_one'),
                              _buildMallItem(1,'${message['user7']}','ic_order_two'),
                              _buildMallItem(2,'${message['user8']}','ic_order_three'),
                              _buildMallItem(3,'${message['user9']}','ic_order_four'),
                            ],
                          )
                        ],
                      ),
                    ),
                  ),

                  
                  SliverToBoxAdapter(
                    child: Container(
                      margin: EdgeInsets.all(12),
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(6)),
                          color: Colors.white
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("${message['user10']}",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16),),
                          SizedBox(height: 8,),
                          Divider(thickness: 1,),
                          SizedBox(height: 6,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              _buildMallItem(4,'${message['user11']}','ic_action_pwd',phone: data.phone),
                              _buildMallItem(5,'${message['user12']}','ic_action_address'),
                              _buildMallItem(6,'${message['user13']}','ic_action_service'),
                              _buildMallItem(7,'${message['user14']}','ic_action_version'),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            );
          }
        )
      ),
    );
  }

  Widget _buildMallItem(index,title, image, {String phone}) {
    return ImageLabel(
      color: Colors.white,
      height: 88,
      width: 65,
      text: Text(
        title,
        style: TextStyle(fontSize: 13, color: HexColor("#666666")),
      ),
      image: Image.asset(
        Utils.getImgPath(image),
        height: 22,
      ),
      onPressed: () {
        switch (index) {
          case 0:
            NavigatorUtil.navigateToPage(context, ProductOrderListPage(index: 0,));
            break;
          case 1:
            NavigatorUtil.navigateToPage(context, ProductOrderListPage(index: 1,));
            break;
          case 2:
            NavigatorUtil.navigateToPage(context, ProductOrderListPage(index: 2,));
            break;
          case 3:
            NavigatorUtil.navigateToPage(context, ProductOrderListPage(index: 3,));
            break;
          case 4:
            NavigatorUtil.navigateToPage(context, ChangePassWordPage(phone: phone,));
            break;
          case 5:
            NavigatorUtil.navigateToPage(context, AddressManagerPage());
            break;
          case 6:
            // NavigatorUtil.navigateToPage(context, TradPaymentPage());
            NavigatorUtil.navigateToPage(context, PaymentMethedPage());
            break;
          case 7:
            NavigatorUtil.navigateToPage(context, VersionPage());
            break;
        }
      },
    );
  }

  Widget _buildFlexibleSpace(UserInfoModel model){
    return FlexibleSpaceBar(
      background: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(Utils.getImgPath('ic_user_top_bg'), fit: BoxFit.fill),
          Positioned(
            top: 90,
            left: 25,
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(38.0), // 定义圆角半径
                  child: Container(
                    height: 40,
                    width: 40,
                    color: Colors.white,
                    child: Image.asset(Utils.getImgPath('ic_logo'),width: 40,height: 40,),
                  )
                ),
                SizedBox(width: 12,),
                Text(
                  "${model.username}",
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
                SizedBox(height: 6,),
                Container(
                    padding: EdgeInsets.only(left: 5,right: 5,top: 1,bottom: 1),
                    margin: EdgeInsets.only(left: 6),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [HexColor("#1B2552"), HexColor("#354273")],
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(25)),
                    ),
                    child: GestureDetector(
                        onTap: (){

                        },
                        child: Row(
                          children: [
                            Image.asset(Utils.getImgPath("ic_user_zc"),width: 17,height: 17,),
                            // SizedBox(width: 1,),
                            Text("${model?.level_title ?? '暂无'}",style: TextStyle(color: HexColor("#C8B274"),fontSize: 13),),
                          ],
                        )
                    )
                )
              ],
            ),
          ),
          Positioned(
            bottom: 30,
            left: 20,
            right: 20,
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(child: Container(child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text("${message['user1']}",style: TextStyle(color: Colors.white),),
                        SizedBox(height: 6,),
                        Text("${Utils.formatLuckCharCount(double.parse(model.money).round())}",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold,color: Colors.white),),
                      ],
                    ).addGesture(() {
                      NavigatorUtil.navigateToPage(context, FundsListPage(type: "1",title:"${message['user19']}"));
                    })
                    ,alignment: Alignment.center,)),
                    Expanded(child: Container(child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text("${message['user21']}",style: TextStyle(color: Colors.white),),
                        SizedBox(height: 6,),
                        Text("${Utils.formatLuckCharCount(double.parse(model.usdt).round())}",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold,color: Colors.white),),
                      ],
                    ).addGesture(() {
                      NavigatorUtil.navigateToPage(context, FundsListPage(type: "2",title:"${message['user22']}"));
                    })
                      ,alignment: Alignment.center,)),
                    Expanded(
                      child: Container(
                        alignment: Alignment.center,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text("${message['user15']}",style: TextStyle(color: Colors.white),),
                            SizedBox(height: 6,),
                            Text("${Utils.formatLuckCharCount(double.parse(model.myr).round())}",style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold,color: Colors.white),),
                          ],
                        ).addGesture(() {
                          NavigatorUtil.navigateToPage(context, FundsListPage(type: "3",title:"交易积分明细"));
                        })
                      )
                    )
                  ],
                ),
                SizedBox(height: 8,),
                Container(
                  height: 5,
                  child: Text(""),
                ),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text("${message['user20']}",style: TextStyle(fontSize: 15,color: HexColor("#FED0D0"),decoration: TextDecoration.underline),).addGesture(() {
                      NavigatorUtil.navigateToPage(context, TransferMoneyPage(phone: model.phone,)).then((value){
                        if(value != null){
                          BlocProvider.of<UserInfoBloc>(ctx).add(HttpEvent());
                        }
                      });
                    }),
                    SizedBox(width: 25,),
                    Container(
                      height: 16,
                      width: 1,
                      color: HexColor("#FED0D0"),
                    ),
                    SizedBox(width: 25,),
                    Text("${message['user2']}",style: TextStyle(fontSize: 15,color: HexColor("#FED0D0"),decoration: TextDecoration.underline),).addGesture(() {
                      NavigatorUtil.navigateToPage(context, ExchangeMoneyPage()).then((value){
                        if(value != null){
                          BlocProvider.of<UserInfoBloc>(ctx).add(HttpEvent());
                        }
                      });
                    })
                  ],
                )
              ],
            )
          )
        ],
      ),
    );
  }
}
